package cc.comac.mom.service.impl;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cc.comac.mom.api.QualityAttachmentService;
import cc.comac.mom.bean.QualityAttachment;
import cc.comac.mom.bean.QualityAttachmentGroup;
import cc.comac.mom.config.OSSService;
import cc.comac.mom.datahandlers.entity.QualityAttachmentDataHandler;
import cc.comac.mom.datahandlers.entity.QualityAttachmentGroupDataHandler;
import cc.comac.mom.entity.QualityAttachmentEntity;
import cc.comac.mom.util.ResultBean;

@Service
@RestController
public class QualityAttachmentServiceImpl implements QualityAttachmentService {

	@Autowired
	private QualityAttachmentDataHandler qualityAttachmentDataHandler;
	
	@Autowired
	private QualityAttachmentGroupDataHandler qualityAttachmentGroupDataHandler;

	@Value("${upload.tempDir}")
	private String rootPath;
	
	@Autowired
	private OSSService oSSService;

	@Override
	public ResultBean uploadFile(@RequestPart("files") MultipartFile[] files) {
		ArrayList<QualityAttachment> listQualityAttachment = new ArrayList<QualityAttachment>();
		// 获取文件全名称
		for (MultipartFile file : files) {
			String path = "";
			try {
				path = oSSService.uploadFileOss(file);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			String originalFilename = file.getOriginalFilename();
			String uuid = UUID.randomUUID().toString();
			try {
				// 获取文件路径名
//				String path = rootPath + File.separator + "upload" + File.separator + uuid + originalFilename;
				// 将文件写入
				URL url = oSSService.getUrl(path);
				URLConnection openConnection = url.openConnection();
				int contentLength = openConnection.getContentLength();
				File file2 = new File(url.toString());
//				if (!file2.getParentFile().exists()) {
//					file2.getParentFile().mkdirs();
//				}
				System.out.println(">>>>>>>>>>>>>>>获取的长度"+contentLength);
				
//				file.transferTo(file2);

				// 保存文档信息
				DecimalFormat df = new DecimalFormat("0.00");
//				String formatMB = df.format((float) file2.length() / 1048576);
				String formatMB = df.format((float) contentLength / 1048576);
				QualityAttachment qualityAttachment = new QualityAttachment();
				QualityAttachmentEntity qualityAttachmentEntity = new QualityAttachmentEntity();
				qualityAttachmentEntity.setFilePath(path);
				qualityAttachmentEntity.setFileSize(formatMB + "MB");
				qualityAttachmentEntity.setRealName(originalFilename);
				qualityAttachmentEntity.setSysName(uuid + originalFilename);
				qualityAttachment.setInnerData(qualityAttachmentEntity);
				listQualityAttachment.add(qualityAttachment);
			} catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException(e.getMessage());
			}

		}
		return qualityAttachmentDataHandler.insertBatch(listQualityAttachment);

	}
	@Override
	public ResultBean uploadFileNoGroup(MultipartFile[] files) {
		ResultBean resultBean = new ResultBean(true);
		ArrayList<QualityAttachment> listQualityAttachment = new ArrayList<QualityAttachment>();
		// 获取文件全名称
		for (MultipartFile file : files) {
			String originalFilename = file.getOriginalFilename();
			String uuid = UUID.randomUUID().toString();
			try {
				// 获取文件路径名
				String path = rootPath + File.separator + "upload" + File.separator + uuid + originalFilename;
				// 将文件写入
				File file2 = new File(path);
				if (!file2.getParentFile().exists()) {
					file2.getParentFile().mkdirs();
				}
				file.transferTo(file2);

				// 保存文档信息
				DecimalFormat df = new DecimalFormat("0.00");
				String formatMB = df.format((float) file2.length() / 1048576);
				QualityAttachment qualityAttachment = new QualityAttachment();
				QualityAttachmentEntity qualityAttachmentEntity = new QualityAttachmentEntity();
				qualityAttachmentEntity.setFilePath(path);
				qualityAttachmentEntity.setFileSize(formatMB + "MB");
				qualityAttachmentEntity.setRealName(originalFilename);
				qualityAttachmentEntity.setSysName(uuid + originalFilename);
				qualityAttachment.setInnerData(qualityAttachmentEntity);
				listQualityAttachment.add(qualityAttachment);
			} catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException(e.getMessage());
			}

		}
		resultBean.setObject(listQualityAttachment);
		return resultBean;
	}
	
	@Override
	public ResultBean deleteFileByAttachmentId(@RequestParam long attachmentId) {
		return qualityAttachmentDataHandler.deleteByAttachmentId(attachmentId);
	}

	@Override
	public ResultBean getByAttachmentGroupId(@RequestParam long groupId) {
		ResultBean resultBean = new ResultBean(true);
		List<QualityAttachmentGroup> attachmentGroupId = qualityAttachmentGroupDataHandler.getByAttachmentGroupId(groupId);
		resultBean.setObject(attachmentGroupId);
		return resultBean;
	}
	
	@Override
	public QualityAttachmentEntity getByAttachmentId(@RequestParam Long attachmentId) {
		ResultBean resultBean = new ResultBean(true);
		QualityAttachmentEntity byId = qualityAttachmentDataHandler.getById(attachmentId);
		resultBean.setObject(byId);
		return byId;
	}

	@Override
	public ResultBean download(@RequestParam Long attachmentId, HttpServletResponse response) {
		ResultBean resultBean = new ResultBean(true);
		ArrayList<Long> listIds = new ArrayList<Long>();
		listIds.add(attachmentId);
		List<QualityAttachment> byAttachmentIds = qualityAttachmentDataHandler.getByAttachmentIds(listIds);
		if(byAttachmentIds == null || byAttachmentIds.size()<1) {
			resultBean.setErrorCode("附件信息不存在");
			return resultBean;
		}
		QualityAttachment qualityAttachment = byAttachmentIds.get(0);
		
		// 获取文件上传路径和真实文件名
		String path = qualityAttachment.getInnerData().getFilePath();
		String realName = qualityAttachment.getInnerData().getRealName();
		try {
			// path是指欲下载的文件的路径。
			File file = new File(path);
			// 取得文件名。
	//		String filename = file.getName();
			// 取得文件的后缀名。
	//		String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
			// 以流的形式下载文件。
			InputStream fis = new BufferedInputStream(new FileInputStream(path));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			response.reset();
			// 设置response的Header
			response.addHeader("Content-Disposition",
					"attachment;filename=" + new String(realName.getBytes("UTF-8"), "ISO8859-1"));
			response.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return resultBean;
	}



}
